<?php

namespace control;

//管理员后台 - 客户账号
class clientStoreClass extends adIndexClass
{
	private const page  = 'clientStore';  # 权限
	private const table = 'store_client'; # 数据表
	private const title = '客户账号';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'          => [
                        'name'  => '客户名称',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'tel' => [
                        'name'  => "手机号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'userName'  => [
                        'name'  => "用户名",
                        'width' => 300,
                    ],
                    'roleId'         => [
                        'name'  => '角色',
                        'width' => 300,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户名称" => text(array("name" => "name")),
                    "手机号"   => text(array("name" => "tel")),
                    "用户名"   => text(array("name" => "userName")),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*成本表列表-查询条件*/
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = '';
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('".self::page."','editPage')\">新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '启用' })\">启用</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '停用'})\">停用</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*成本表列表-查询结果*/
	public function homeSearch(): bool|string
	{
		$where = ' 1=1 ';
		$equal = [
			'state' => $this->post('state'),
		];
		$like  = [
			'name'     => $this->post('name'),
			'tel'      => $this->post('tel'),
			'userName' => $this->post('userName'),
		];
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$page = $this->page([
			"table" => self::table,
			"where" => $where,
			"order" => $orderBy['orderBy'],
		]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "id")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
		foreach ($page['array'] as $array) {
			$dominate = [
				"box"    => [
					"name"  => "id",
					"value" => $array['id'],
				],
				"detail" => [
					"title" => "用户详情",
					"click" => "newIframe('用户详情','" . $url . "&id=" . $array['id'] . "')",
				],
			];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "roleId":
                        $row[] = self::getRoleName($array['roleId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = '';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 获取角色名称
	 *
	 * @param string $ids
	 * @return string
	 */
	public static function getRoleName(string $ids): string
	{
		$roleArray = (array)json_decode($ids, true);
		return end($roleArray);
	}


	/**
	 * 新建
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看权限";
		} elseif (!$this->get('id')) {
			$html = "ID为空";
		} elseif (!$info['id']) {
			$html = "未找到此信息";
		} else {
			$data = [
				"id" => $info['id'],
			];
			//按钮
			$button = [];
			if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name"  => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "editPage",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
				$opt      = ($info['state']) == "停用" ? '启用' : '停用';
				$button[] = [
					"name" => $opt,
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'changeState', "id" => $info['id'], 'state' => $opt],
				];

			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				"基本信息" => [
					[
						"姓名"   => $info['name'],
						"手机号" => $info['tel'],
						"用户名" => $info['userName'],
                        "角色" => self::getRoleName($info['roleId']),
					],
					[
						"备注" => pre($info['text']),
					],
				],
				"系统信息" => [
					[
						"用户编号" => $info['orderNo'],
						'创建人'   => self::findStaff($info['stid']),
						"创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
					],
					[
						'状态'     => $info['state'],
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

    public function editPage()
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        // 角色
        $roleOption = ['客户'];
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "姓名：" => text(['name' => 'name', 'class' => 'text', 'value' => $info['name'],]),
                    must . "手机号：" => text(['name' => 'tel', 'value' => $info['tel']]),
                ],
                [
                    must . "用户名：" => text(["name" => "userName", 'class' => 'text', "value" => $info['userName']]),
                    "密码：" => hidden(['name' => 'password', 'value' => '']) . (!empty($info['id']) ? "<span id='pwd'>***********</span><span class='spanButton' style='margin: 0 0 0 20px' id='copy-btn' data-pas>重置并复制</span>" : para('staffPas') . ' (初始密码)'),
                ],
                [
                    "角色：" => checkbox(["name" => "roleId", 'class' => 'textLong', 'value' => $roleOption, "checked" => json_decode($info['roleId'], true)]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $this->get('id')]),
                ],
            ],
        ]);
        $html .= <<<EOT
        <script src='{$this->root}static/javascript/clipboard.min.js'></script>
        <script>
        let pageCtrl = {
            getPass: function(ele) {
                $.ajax({
                    url: root + 'control/adIndex.html?cla=clientStore&fun=resetPwd',
                    type: 'post',
                    data: {
                        id : $('[name="id"]').val()
                    },
                    dataType: 'json',
                    async: false,
                    success: function(res) {
                        if(res.code == 1){
                            ele.html(res.data)
                        }else{
                            msg(res.msg, 'error')
                        }
                    }
                });
            },
            clip: function() {
                let that = this,
                clipboard = new ClipboardJS('#copy-btn', {
                    text: function(el) {
                        let obj = $('#pwd')
                        obj.empty()
                        that.getPass(obj); //ajax请求并设置要复制的字符串
                        return obj.html()
                    }
                });
                clipboard.on('success', function(e) {
                    console.log(e)
                    msg('密码复制成功')
                    e.clearSelection();
                });
                clipboard.on('error', function(e) {
                    console.log(e)
                    msg('密码复制失败，请手动复制', 'error')
                    e.clearSelection();
                });
            },

            init: function() {
                this.clip();
            }
        };
        $(function() {
            pageCtrl.init();
        });
        
        </script>
EOT;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

	public function resetPwd(): bool|string
	{
		$id   = $this->post('id') ? $this->post('id') : '';
		$data = [
			'code' => 0,
		];
		if (!$id) {
			$data['warn'] = '参数不能为空';
		} elseif (!$this->power(self::page, "edit")) {
			$data['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$temp         = strtolower(substr(self::getId(), 0, 6));
			$password     = str_replace(['o', 'l'], 1, $temp);
			$data['warn'] = static::update([
				'table' => self::table,
				'field' => [
					'password' => md5s($password),
				],
				'where' => " id = '$id' ",
			]);
			if (in_array($data['warn'], ['更新成功', '新增成功'])) {
				$data = [
					'msg'  => '密码重置成功',
					'data' => $password,
					'code' => 1,
				];
			}
		}
		return json_encode($data, 320);
	}


	/*成本表基本资料新增或修改-异步处理*/
	public function editPageEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'name'     => $this->post('name'),
			'userName' => $this->post('userName'),
			'roleId'   => $this->post('roleId') ? json_encode($this->post('roleId'), 320) : '',
			'tel'      => $this->post('tel'),
			//            'password' => $this->post('password'),
			'text'     => $this->post('text'),
		];
		$annotation = [
			'name'     => '姓名',
			'userName' => '用户名',
			'roleId'   => '角色',
			'tel'      => '手机号',
			'password' => '密码',
			'text'     => '备注',
		];
		$rules      = [
			'name'     => 'required',
			'userName' => 'required',
			// 'roleId'     => 'required',
			'tel'      => 'required|unsigned_int',
			// 'password' => 'required',
			// 'text'     => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			if (sqlNum(self::table, " (userName = '{$field['userName']}' OR tel = '{$field['tel']}') AND id <> '$id'   ") > 0) {
				$json['warn'] = "用户名 {$field['userName']} 或 手机号 {$field['tel']} 重复";
				goto resp;
			}

			// 密码不为空
			if ($this->post('password')) {
				$field['password'] = md5s($this->post('password'));
			}
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'YRSQ' . date('Ymd'),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'       => $id,
					'orderNo'  => $orderNo,
					'password' => md5s(para('staffPas')),
					'stid'     => $this->control['stid'],
					'state'    => '启用',
					'time'     => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 操作中转
	 *
	 * @return string
	 */
	public function operate(): string
	{
		$act    = $this->post('act') ?? '';
		$pwd    = false; // 需要密码
		$form   = $power = '';
		$append = [];
		switch ($act) {
			case 'changeState':
				$act      = 'state';
				$msg      = self::title . '修改状态';
				$title    = self::table . 'Change';
				$function = 'changeState';
				$form     = 'userOperateForm, listForm';
				if ($this->post('state')) {
					$append = [
						0 => hidden(['name' => 'state', 'value' => $this->post('state')]),
					];
				}
				$power = '';
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::table . 'Delete';
				$function = 'isDelete';
				$form     = 'userOperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 修改状态
	 *
	 * @return string
	 */
	public function changeState(): string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$state = $this->post('state');
		$act   = 'state';
		$json  = [];
		if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 修改field
			$fieldKey = 'state';
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info['state'] == $state) {
						continue;
					}
					$fieldVlaue = ($info['state'] == '启用') ? '停用' : '启用';
					// 修改状态
					static::update([
						"table" => self::table,
						'field' => [
							$fieldKey => $fieldVlaue,
						],
						"where" => $where,
					]);
					//添加记录
					$text .= "管理员{$this->control['name']}修改了一条" . self::title . "：ID【{$id}】<br>";
					$x++;
				}
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "修改了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		resp:
		return json_encode($json, 320);
	}


	/**
	 * 确认删除信息
	 *
	 * @return string
	 */
	public function isDelete(): string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 判断field
			$fieldKey   = 'state';
			$fieldVlaue = '启用';

			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info[$fieldKey] == $fieldVlaue) {
						$text .= self::title . "【{$info['id']}】为{$fieldVlaue}状态，无法删除<br>";
						continue;
					}
					if ($info['isDel']) {
						$text .= self::title . "【{$info['id']}】为超级管理员账号，无法删除<br>";
						continue;
					}
					// 删除相关 附件
					// $result = (array) $this->sqlFind("SELECT id, src FROM `attachFile` WHERE targetId = '{$info['id']}' ");
					// foreach ($result as $key => $attachFile) {
					//     delete([
					//         'table' => 'attachFile',
					//         'where' => " id = '{$attachFile['id']}'",
					//     ]);
					//     fileDelete($attachFile['src']);
					// }
					// 删除子表
					// delete([
					//     "table" => self::table.'Mx',
					//     "where" => " orderId = '$id' "
					// ]);
					// 删除表
					delete([
						"table" => self::table,
						"where" => $where,
					]);
					//添加记录
					$text .= "管理员{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】<br>";
					$x++;
				}
			}

			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}

		resp:
		return json_encode($json, 320);
	}
}
